<template>
	<div class="container">
	    <div class="header">
	      <h1>身份验证</h1>
	      <p>正在验证二维码信息...</p>
	    </div>
	    
	    <div class="content">
	      <!-- 加载状态 -->
	      <div v-if="loading" class="status-container">
	        <div class="loader"></div>
	        <p>验证中，请稍候...</p>
	      </div>
	      
	      <!-- 验证结果 -->
	      <div v-else class="result-container">
	        <div class="status-icon" :class="resultClass">
	          {{ resultIcon }}
	        </div>
	        <h2>{{ resultTitle }}</h2>
	        <p>{{ resultMessage }}</p>
	        
	        <!-- 显示二维码信息 -->
	        <div v-if="qrData" class="info-box">
	          <h3>二维码信息</h3>
	          <div class="info-item">
	            <span class="label">Token:</span>
	            <span class="value">{{ qrData.token }}</span>
	          </div>
	          <div class="info-item">
	            <span class="label">生成时间:</span>
	            <span class="value">{{ formatTime(qrData.timestamp) }}</span>
	          </div>
	          <div class="info-item">
	            <span class="label">扫描时间:</span>
	            <span class="value">{{ formatTime(scanTime) }}</span>
	          </div>
	          <div class="info-item">
	            <span class="label">有效期:</span>
	            <span class="value" :class="{ 'text-danger': isExpired }">
	              {{ timeRemaining }}
	            </span>
	          </div>
	        </div>
	      </div>
	      
	      <!-- 操作按钮 -->
	      <div class="action-buttons">
	        <!--<button v-if="verificationResult === 'success'" class="btn btn-success" @click="handleSuccess">
	          进入系统
	        </button> -->

	      </div>
	    </div>
		<div class="footer">
		  <!--<p>© 2023 UniApp二维码验证系统 | 安全可靠的身份验证解决方案</p> -->
		  <a href="https://beian.miit.gov.cn" class="beian-link" target="_blank">
		        <span class="beian-icon"></span>
		        冀ICP备2024093937号-1
		  </a>
		  
		</div>
	  </div>
</template>

<script>
	export default {
		name: 'VerifyPage',
		data() {
			return {
				  loading: true,
				  verificationResult: null, // null, 'success', 'failure', 'expired'
				  qrData: null,
				  scanTime: Date.now(),
				  errorMessage: ''
			}
		},
		computed: {
		    resultClass() {
		      switch (this.verificationResult) {
		        case 'success': return 'success';
		        case 'failure': return 'failure';
		        case 'expired': return 'expired';
		        default: return 'pending';
		      }
		    },
		    resultIcon() {
		      switch (this.verificationResult) {
		        case 'success': return '✓';
		        case 'failure': return '✗';
		        case 'expired': return '⏰';
		        default: return '⋯';
		      }
		    },
		    resultTitle() {
		      switch (this.verificationResult) {
		        case 'success': return '验证成功';
		        case 'failure': return '验证失败';
		        case 'expired': return '二维码已过期';
		        default: return '验证中';
		      }
		    },
		    resultMessage() {
		      switch (this.verificationResult) {
		        case 'success': return '您的身份已验证成功，欢迎访问系统';
		        case 'failure': return '无效的验证请求，请扫描有效的二维码';
		        case 'expired': return '此二维码已超过有效期，请获取新的二维码';
		        default: return '正在验证二维码信息...';
		      }
		    },
		    isExpired() {
		      if (!this.qrData) return false;
		      return Date.now() - this.qrData.timestamp > 60000;
		    },
		    timeRemaining() {
		      if (!this.qrData) return '--';
		      const remaining = Math.max(0, 60000 - (Date.now() - this.qrData.timestamp));
		      return `${Math.ceil(remaining / 1000)} 秒`;
		    }
		  },
		  mounted() {
		    this.verifyQRCode();
		  },
		  methods: {
		    // 解析URL参数
		    parseUrlParams() {
		      const urlParams = new URLSearchParams(window.location.search);
		      
		      return {
		        token: urlParams.get('token'),
		        time: urlParams.get('time'),
		        source: urlParams.get('source')
		      };
		    },
		    
		    // 格式化时间
		    formatTime(timestamp) {
		      if (!timestamp) return '--';
		      const date = new Date(parseInt(timestamp));
		      return date.toLocaleString('zh-CN', {
		        year: 'numeric',
		        month: '2-digit',
		        day: '2-digit',
		        hour: '2-digit',
		        minute: '2-digit',
		        second: '2-digit'
		      });
		    },
		    
		    // 验证二维码
		    async verifyQRCode() {
		      try {
		        this.loading = true;
		        
		        // 1. 解析URL参数
		        const params = this.parseUrlParams();
		        
		        // 2. 检查是否通过二维码访问
		        if (params.source !== 'qr') {
		          this.verificationResult = 'failure';
		          this.errorMessage = '不是通过二维码访问';
		          return;
		        }
		        
		        // 3. 检查参数完整性
		        if (!params.token || !params.time) {
		          this.verificationResult = 'failure';
		          this.errorMessage = '缺少必要的验证参数';
		          return;
		        }
		        
		        // 4. 保存二维码数据
		        this.qrData = {
		          token: decodeURIComponent(params.token),
		          timestamp: parseInt(params.time)
		        };
		        
		        // 5. 检查二维码是否过期
		        const currentTime = Date.now();
		        const qrAge = currentTime - this.qrData.timestamp;
		        
		        if (qrAge > 60000) { // 1分钟
		          this.verificationResult = 'expired';
		          this.errorMessage = `二维码已过期 ${Math.ceil(qrAge / 1000)} 秒`;
		          return;
		        }
				uni.navigateTo({
				  //url: '/pages/sign-in/sign-in?token=' + encodeURIComponent(this.qrData.token)
				  url: '/pages/sign-in/sign-in'
				});
		        
		        // 6. 模拟服务器验证（实际项目中调用API）
		        /* const isValid = await this.validateWithServer(this.qrData.token, this.qrData.timestamp);
		        
		        if (isValid) {
		          this.verificationResult = 'success';
		        } else {
		          this.verificationResult = 'failure';
		          this.errorMessage = '服务器验证失败';
		        } */
				
		        
		      } catch (error) {
		        console.error('验证过程中出错:', error);
		        this.verificationResult = 'failure';
		        this.errorMessage = error.message || '验证过程出现异常';
		      } finally {
		        this.loading = false;
				//调整失败界面
				uni.navigateTo({
				  //url: '/pages/sign-in/sign-in?token=' + encodeURIComponent(this.qrData.token)
				  url: '/pages/sign-in-error/sign-in-error'
				});
		      }
		    }
		    
		    // 模拟服务器验证
		    /* async validateWithServer(token, timestamp) {
		      // 实际项目中这里应该是真实的API调用
		      try {
		        // 模拟网络请求延迟
		        await new Promise(resolve => setTimeout(resolve, 1000 + Math.random() * 1000));
		        
		        // 模拟服务器验证逻辑
		        // 这里可以添加更复杂的验证逻辑，比如检查token格式、时间戳有效性等
		        
		        // 简单的验证：检查token长度和时间戳范围
		        const isValidToken = token && token.length >= 20;
		        const isValidTime = timestamp > Date.now() - 60000 && timestamp <= Date.now();
		        
		        return isValidToken && isValidTime;
		        
		      } catch (error) {
		        console.error('服务器验证失败:', error);
		        return false;
		      }
		    } */
		    
		    // 处理成功
		    /* handleSuccess() {
		      // 在实际项目中，这里可以跳转到主页面或执行其他成功操作
		      console.log('验证成功，token:', this.qrData.token);
		      
		      // 示例：跳转到成功页面
		      uni.navigateTo({
		        url: '/pages/success/index?token=' + encodeURIComponent(this.qrData.token)
		      });
		    } */
		  }
	}
</script>

<style scoped>
.container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
  display: flex;
  flex-direction: column;
}

.header {
  text-align: center;
  color: white;
  margin-bottom: 30px;
}

.header h1 {
  font-size: 28px;
  margin-bottom: 10px;
}

.header p {
  opacity: 0.9;
}

.content {
  flex: 1;
  background: white;
  border-radius: 20px;
  padding: 30px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
}

.status-container {
  text-align: center;
  padding: 40px 0;
}

.result-container {
  text-align: center;
  padding: 20px 0;
}

.status-icon {
  font-size: 80px;
  margin-bottom: 20px;
}

.status-icon.success {
  color: #4CAF50;
  animation: successPulse 0.6s ease-in-out;
}

.status-icon.failure {
  color: #F44336;
}

.status-icon.expired {
  color: #FF9800;
}

.status-icon.pending {
  color: #2196F3;
}

@keyframes successPulse {
  0% { transform: scale(0.8); opacity: 0; }
  50% { transform: scale(1.2); }
  100% { transform: scale(1); opacity: 1; }
}

.result-container h2 {
  margin: 15px 0;
  color: #333;
  font-size: 24px;
}

.result-container p {
  color: #666;
  margin-bottom: 30px;
  font-size: 16px;
}

.info-box {
  background: #f8f9fa;
  border-radius: 12px;
  padding: 20px;
  margin: 20px 0;
  text-align: left;
}

.info-box h3 {
  margin-bottom: 15px;
  color: #333;
  border-bottom: 2px solid #e9ecef;
  padding-bottom: 10px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12px;
  padding-bottom: 12px;
  border-bottom: 1px dashed #dee2e6;
}

.info-item:last-child {
  margin-bottom: 0;
  padding-bottom: 0;
  border-bottom: none;
}

.label {
  color: #666;
  font-weight: 500;
  flex-shrink: 0;
}

.value {
  color: #333;
  font-weight: bold;
  word-break: break-all;
  text-align: right;
  max-width: 60%;
}

.text-danger {
  color: #F44336 !important;
}

.action-buttons {
  margin-top: 30px;
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.btn {
  padding: 15px;
  border: none;
  border-radius: 10px;
  font-size: 16px;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s;
}

.btn-success {
  background: linear-gradient(to right, #4CAF50, #45a049);
  color: white;
}

.btn-primary {
  background: linear-gradient(to right, #2196F3, #1976D2);
  color: white;
}

.btn-secondary {
  background: #f8f9fa;
  color: #666;
  border: 1px solid #dee2e6;
}

.btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
}

.loader {
  border: 4px solid #f3f3f3;
  border-top: 4px solid #2196F3;
  border-radius: 50%;
  width: 50px;
  height: 50px;
  animation: spin 1s linear infinite;
  margin: 0 auto 20px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

@media (max-width: 600px) {
  .container {
    padding: 10px;
  }
  
  .content {
    padding: 20px;
  }
  
  .header h1 {
    font-size: 24px;
  }
  
  .status-icon {
    font-size: 60px;
  }
  
  .info-item {
    flex-direction: column;
    gap: 5px;
  }
  
  .value {
    max-width: 100%;
    text-align: left;
  }
  /* 底部样式 */
  .footer {
    text-align: center;
    padding: 20px;
    color: #666;
    font-size: 12px;
    border-top: 1px solid #eee;
  }
}
</style>
